/*
 * @Author: WangGuojian 1085844536@qq.com
 * @Date: 2022-09-20 11:30:50
 * @LastEditTime: 2022-09-20 11:45:38
 * @LastEditors: WangGuojian 1085844536@qq.com
 * @FilePath: \pro05-demo-all-in-one\src\main\java\com\atguigu\imperial\court\servlet\base\ViewBaseServlet.java
 * @Description:处理模板文件的 Servlet 基类
 */
package com.atguigu.imperial.court.servlet.base;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ViewBaseServlet extends HttpServlet {

    private TemplateEngine templateEngine;

    @Override
    public void init() throws ServletException {

        // 1.获取 ServletContext 对象
        ServletContext servletContext = this.getServletContext();

        // 2.创建 Thymeleaf 解析器对象
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);

        // 3.给解析器对象设置参数
        // ①HTML 是默认模式，明确设置是为了代码更容易理解
        templateResolver.setTemplateMode(TemplateMode.HTML);

        // ②设置前缀
        String viewPrefix = servletContext.getInitParameter("view-prefix");

        templateResolver.setPrefix(viewPrefix);

        // ③设置后缀
        String viewSuffix = servletContext.getInitParameter("view-suffix");

        templateResolver.setSuffix(viewSuffix);

        // ④设置缓存过期时间（毫秒）
        templateResolver.setCacheTTLMs(60000L);

        // ⑤设置是否缓存
        templateResolver.setCacheable(true);

        // ⑥设置服务器端编码方式
        templateResolver.setCharacterEncoding("utf-8");

        // 4.创建模板引擎对象
        templateEngine = new TemplateEngine();

        // 5.给模板引擎对象设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

    protected void processTemplate(String templateName, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 1.设置响应体内容类型和字符集
        response.setContentType("text/html;charset=utf-8");

        // 2.创建WebContext对象
        WebContext webContext = new WebContext(request, response, getServletContext());

        // 3.处理模板数据
        templateEngine.process(templateName, webContext, response.getWriter());

    }
}
